

var u = null;
var urlUnity="http://localhost:8080/asset/";
var isShowPeiXian = false;
//3D控件初始化回调
function on3dInitReady(isSuccessful) {
  if(isSuccessful) {
     loadScene();
  }
}


//加载场景
function loadScene() {
	var scene = {
    "Code": "earth",   
	};	
	u.getUnity().SendMessage("Root", "LoadScene", JSON.stringify(scene));
}

//加载场景后的回调，用来判断当前点击的是哪个场景
//回调事件群
var windowsceneCode = false;
function onLoadScene(sceneCode, isSuccessful, errorCode, errorMsg, sceneType, isEmpty, roomNames, boxName) {//加载场景回调
  if(isSuccessful) {
	  windowsceneCode = sceneCode;
	if(sceneCode=="room-unicom-6f"){
	    createRackAndServers(sceneCode);
	 }else if(sceneCode=="room-unicom-real"){
	    createRackAndServers(sceneCode);
	 }else if(sceneCode=="room-haiguan"){
	    createRackAndServers(sceneCode);
	 }else if(sceneCode=="room-yancaon"){
	    createRackAndServers(sceneCode);
	 }
  }
}
function createRackAndServers(name) {  
	    var clearbubbles=[];
		var clearlabels=[];
		var cc =alarmServer.keySet();
		for(var i=0;i<cc.length;i++){
			if(alarmServer.containsKey(cc[i])){
					// 清除报警
					clearbubbles.push({Code: cc[i]});
					// 清除缓存报警服务器
					alarmServer.remove(cc[i],1);
				}
		}
		if(clearbubbles.length > 0){		
			u.getUnity().SendMessage("Root", "ClearGlowBox", JSON.stringify(clearbubbles));
		}
		var bb =alarmRack.keySet();
		for(var j=0;j<bb.length;j++){
			if(alarmRack.containsKey(bb[j])){
				clearlabels.push({Code:bb[j],LabelType:"warning"})
				// 删除缓存
				alarmRack.remove(bb[j]);
			}
		}
		if(clearlabels.length > 0){		
			u.getUnity().SendMessage("Root", "HideObjectLabels", JSON.stringify(clearlabels));
		}
		$.getJSON(urlUnity+'api/queryRackFor3D?roomCode='+name, function(data,status){
		  window.rack = []; window.server = [];
          for(var i=0;i<data.data.length;i++){
				if(data.data[i].Type == "Rack"){
				 rack.push(data.data[i])
				}else if(data.data[i].Type == "Server"){
				 server.push(data.data[i])
				}
          }
       
		//   $.getJSON('unity/resources/Config/'+name+'.json'+"?t="+new Date().getTime(), function(data,status){
		// 	var arr = rack.concat(data.Objects.concat(server))
		// 	//console.log(JSON.stringify(arr));
		// 	function timeout(){
		// 	  u.getUnity().SendMessage("Root", "LoadObjects", JSON.stringify(arr));
		// 	}
		// 	setTimeout(timeout,3000)		
		//   });	  
		var arr = rack.concat(server)
		//console.log(JSON.stringify(arr));
		function timeout(){
		  u.getUnity().SendMessage("Root", "LoadObjects", JSON.stringify(arr));
		}
		setTimeout(timeout,3000)	

		});	
}

var selectCode,selectType;
function onShowBizView(code,type){//设备选中回调
		if(type=="Rack"||type=="Server"){
			    var infoR = {'Title':'机柜信息示例','ObjType':type,'Code':code};
				var infoS = {'Title':'服务器信息示例','ObjType':type,'Code':code};
				var info = (type=='Rack')?infoR:infoS;
				u.getUnity().SendMessage("Canvas", "ShowInfoPanel", JSON.stringify(info));
				selectCode = code;
				selectType = type;
				var arrt = {"Attributes":[]};
				u.getUnity().SendMessage("Canvas", "ShowInfoPanelInfo", JSON.stringify(arrt));
				onInfoPanelTabsShow("info")
		}
}

function onInfoPanelTabsShow(type){
	var  attrPairs = [],arrt;
	if (type == "info"){
		if(selectType=='Rack'){				
			$.getJSON(urlUnity+'api/getRackInfo?rackCode='+selectCode, function(data,status){				
			    if(data&&data.httpCode==200 ){
			      var dataobj = data.data, attrPairs = [];
			      for(var i in dataobj) {
			    	  attrPairs.push({Text1: decodeURI(i),Text2: decodeURI(dataobj[i])})
				  }
			      var arrt = {"Attributes":attrPairs};
				 // console.log(JSON.stringify(arrt));
			      u.getUnity().SendMessage("Canvas", "ShowInfoPanelInfo", JSON.stringify(arrt));
			    }
			 });
		
		}else{
			$.getJSON(urlUnity+'api/getServerInfo?serverCode='+selectCode, function(data,status){
			    if(data && data.httpCode==200){
			    var dataobj = data.data,attrPairs = [];
				   for(var i in dataobj) {
					   attrPairs.push({Text1: decodeURI(i),Text2: decodeURI(dataobj[i])})
				   }
				   var arrt = {"Attributes":attrPairs};
				   //console.log(JSON.stringify(arrt));
				   u.getUnity().SendMessage("Canvas", "ShowInfoPanelInfo", JSON.stringify(arrt));
				}
			});
	
		}
		
	}
}

//创建配线演示
function wiringDemo(){
	u.getUnity().SendMessage("Root", "CreateServerPorts",JSON.stringify(
		{'Code':'942601044921520128',
		 'Ports':[
				{'Code':'port-1','Position':{'x':-0.1712894,'y':0.02080382,'z':-0.3177605}}
		 ]}));
	u.getUnity().SendMessage("Root", "CreateServerPorts",JSON.stringify({
		 'Code':'911449961055207586',
		 'Ports':[
				{'Code':'port-1','Position':{'x':0.04264645,'y':0.02090693,'z':-0.3177586}}
		 ]}
	));
	
	u.getUnity().SendMessage("Root", "BlurAllExcept",JSON.stringify([
				{'Code':'942601044921520128'},
				{'Code':'911449961055207586'}
		   ])
	);
	
	u.getUnity().SendMessage("Root", "WiringCreate",JSON.stringify(
			{'Code':'78K0PW5-port-1~201705-1057-port1',
			 'Start':{'Server':'942601044921520128','Port':'port-1'},
			 'End':{'Server':'911449961055207586','Port':'port-1'},
			 'Path':['892056339570577413','892056339570577413','892056339570577169']
		    }
	));
	
}

function wiringDemoEnd(){
	u.getUnity().SendMessage("Root", "Normal","");
	u.getUnity().SendMessage("Root", "WiringDelete","78K0PW5-port-1~201705-1057-port1")
}


function showAlarmMessageFn(data){	
	if(data.roomCode == windowsceneCode){
		showWarningFn(data.rackCode,data.clearServerId,data.alarmServerIds,data.alarmCount);
	}	
}


function downData(rackCode,dataList){	
	if(dataList&&dataList.length > 0 ){
		var downServerInfo=[];
		for(var i=0;i<dataList.length;i++){	
			downServerInfo.push({Code: dataList[i].Code});		
		}
		u.getUnity().SendMessage("Root", "UnloadObjects", JSON.stringify(downServerInfo));
	}
}


//上架显示服务器
// 缓存的服务器
var currentServer = new HashMap();
function upData(rackCode,dataList){
	console.log(currentServer);
	var upServerInfo=[];
	var downServerInfo=[];
	if(dataList&&dataList.length > 0 ){	
		var serverList=currentServer.getList(rackCode);
		console.log(serverList+"有盘盈的标签");
		for(var i=0;i<dataList.length;i++){	
			if(serverList.length>0){			
				if(serverList.indexOf(dataList[i].Code)==-1){
					serverList.push(dataList[i].Code);
					//设置要上架的设备信息
					upServerInfo.push(dataList[i]);
				}
				else{
					//执行下架
					downServerInfo.push({Code: dataList[i].Code});
				}
			}else{
				serverList.push(dataList[i].Code);
				//设置要上架的设备信息
				upServerInfo.push(dataList[i]);
			}			
		}
		currentServer.put(rackCode,serverList);
		u.getUnity().SendMessage("Root", "UnloadObjects", JSON.stringify(downServerInfo));

	}else{
		//如果没有盘盈盘亏，那就把缓存机柜和服务器信息取出来 执行下架操作
		var serverList=currentServer.getList(rackCode);
		if(serverList&&serverList.length > 0){
           // 删除缓存,执行下架
			currentServer.remove(rackCode);			
			for(var i=0;i<serverList.length;i++){	
				downServerInfo.push({Code: serverList[i]});
			}	
			u.getUnity().SendMessage("Root", "UnloadObjects", JSON.stringify(downServerInfo));
		}
	}
	// 显示上架设备
	if(upServerInfo.length > 0){
		console.log(JSON.stringify(upServerInfo));
		u.getUnity().SendMessage("Root", "LoadObjects", JSON.stringify(upServerInfo));
	}		
}



// 当前有报警服务器
var alarmServer = new HashMap();
// 当前有报警的机柜
var alarmRack =  new HashMap();

function showWarningFn(rackCode,clears,alarms,alarmCount){
	debugger;
	var bubbles=[];
	var clearbubbles=[];
	var warninglabels=[];
	var clearlabels=[];
  // 查看机柜报警，有报警存储机柜code，设置报警
	if(alarms&&alarms.length > 0){
		// 如果报警缓存没有，再报警
		if(!alarmRack.containsKey(rackCode)){
			// 设置报警			
			warninglabels.push({Code:rackCode,LabelType:"warning"})
			// 缓存报警的机柜
			alarmRack.put(rackCode,1);
		}
	}else{
		if(alarmCount==0){
          if(alarmRack.containsKey(rackCode)){
			// 清除报警
			clearlabels.push({Code:rackCode,LabelType:"warning"})
			// 删除缓存
			alarmRack.remove(rackCode);
		 }
		}
		
	}
	// 查看服务器报警，有报警存储服务器code，设置报警
	if(alarms&&alarms.length > 0 ){
		for(var i=0;i<alarms.length;i++){
			
			// 如果报警缓存没有，再报警
			if(!alarmServer.containsKey(alarms[i])){
				// 设置报警
				bubbles.push({Code: alarms[i]});
				// 缓存报警服务器
				alarmServer.put(alarms[i],1);
			}
		}
	}
	// 清除报警，如果缓存有移除缓存
	//console.log(JSON.stringify(clears)+"clearbubbles");
	if(clears&&clears.length > 0){
		for(var k=0;k<clears.length;k++){
			// 如果报警缓存有，再清除
			if(alarmServer.containsKey(clears[k])){
				// 清除报警
				clearbubbles.push({Code: clears[k]});
				// 清除缓存报警服务器
				alarmServer.remove(clears[k],1);
			}
		}
	}
	//console.log(JSON.stringify(clearbubbles)+"clearbubbles");
	// 清除报警	
	if(clearbubbles.length > 0){
		u.getUnity().SendMessage("Root", "RemoveGlowBox", JSON.stringify(clearbubbles));
	}	
    // 发送报警
	if(bubbles.length > 0){		
		u.getUnity().SendMessage("Root", "CreateGlowBox", JSON.stringify(bubbles));
	}
	//console.log(JSON.stringify(warninglabels)+"warninglabels");
	if(warninglabels.length > 0){
		u.getUnity().SendMessage("Root", "ShowObjectLabels", JSON.stringify(warninglabels));
	}
	//console.log(JSON.stringify(clearlabels)+"clearlabels");
	if(clearlabels.length > 0){		
		u.getUnity().SendMessage("Root", "HideObjectLabels", JSON.stringify(clearlabels));
	}
}


//关闭面板
function closeBizInfo(bizCode,type){
	u.getUnity().SendMessage("Canvas", "CloseInfoPanel", "");
}

//展开空间占有面板
function showUserdFn(){
	u.getUnity().SendMessage("Canvas", "SetRoomStaticInfo",JSON.stringify(
			{'WarnNum':'18',//报警数量
			 'RoleNum':'9',
			 'PowerUsed':10,
			 'PowerUnused':5,
			 'SpaceUsed':105,
			 'SpaceUnused':124
			}
	     ));
}

//加载每一个机柜和服务器以后的回调
function onLoadObjects(objectsInfo, isSuccess, errCode, errMsg) {
//	console.log("onLoadObjects " + (isSuccess ? ("successfully. " + objectsInfo) : ("failed! " + "[" + errCode + "]" + errMsg)));
}

	window.getiframemsg = function(data){//注册消息接收事件
		//console.log("接到消息："+data);
		if(data){
			wiringDemo();
		}else{
			wiringDemoEnd();
		}
		
    }
function onLoadObjectsComplete (objectsInfo, isSuccess, errCode, errMsg) {
	//showUserdFn();//展开空间占有面板
	$.getJSON(urlUnity+'api/queryCount3D?roomCode='+windowsceneCode, function(data,status){
		if(data && data.httpCode==200 ){
			u.getUnity().SendMessage("Canvas", "SetRoomStaticInfo",JSON.stringify(data.data));
	    }
	});
	//console.log("onLoadObjectsComplete " + (isSuccess ? ("successfully. " + objectsInfo) : ("failed! " + "[" + errCode + "]" + errMsg)));
    window.getiframemsgmd(true); //发送消息

	
		
	$.getJSON(urlUnity+'api/alarm/getAlarm?roomCode='+windowsceneCode, function(data,status){
		var bubbles=[];
		var warninglabels=[];
	    if(data && data.httpCode==200 ){
			//console.log(JSON.stringify(data.data)+"告警信息");
	    	for(var i=0;i<data.data.length;i++){
				// 如果报警缓存没有，再报警
	    		if(!alarmRack.containsKey(data.data[i].rackCode)){
	    			// 设置报警
	    			// bubbles.push({Code: data.returnData[i].rackCode,Color: "ff0000",Flash: 1});
	    			warninglabels.push({Code:data.data[i].rackCode,LabelType:"warning"})
	    			// 缓存报警的机柜
	    			alarmRack.put(data.data[i].rackCode,1);
	    		}
	    		var servers = data.data[i].serverCode.split(",");
	    		for(var k=0;k<servers.length;k++){
	    			// 如果报警缓存没有，再报警
	    			if(!alarmServer.containsKey(servers[k])){
	    				// 设置报警
	    				bubbles.push({Code: servers[k]});
	    				// 缓存报警服务器
	    				alarmServer.put(servers[k],1);
	    			}
	    		}
	    	}

			// 发送报警
			//console.log(JSON.stringify(bubbles)+"告警服务器");
	    	if(bubbles.length > 0){
	    		u.getUnity().SendMessage("Root", "CreateGlowBox", JSON.stringify(bubbles));
			}
			//console.log(JSON.stringify(warninglabels)+"告警机柜");
	    	if(warninglabels.length > 0){
	    		u.getUnity().SendMessage("Root", "ShowObjectLabels", JSON.stringify(warninglabels));
	    	}
	    }
	 });

	 
}


//结束查看设备
function onCloseBizView(objectCode, objectType) {//结束查看设备
	closeBizInfo(objectCode, objectType);
}
function onShowInfoPanelInfo(info){}
function onUnloadObjects(info){}
function onShowInfoPanel(){}
function onSetLight(info){}
function onSetRoomInfo(){}
function onSetColor(){}
function onRemoveGlowBox(objectsInfo, isSuccess, errCode, errMsg){}
function onCreateGlowBox(objectsInfo, isSuccess, errCode, errMsg){}
function onClearGlowBox(objectsInfo, isSuccess, errCode, errMsg){}
function onShowObjectLabels(objectsInfo, isSuccess, errCode, errMsg) {}//显示机柜标签回调
function onHideObjectLabels(objectsInfo, isSuccess, errCode, errMsg) {}//隐藏机柜标签回调
function onSetRoomStaticInfo(){}
function onCreatePort(){}
function onBlurAllExcept(){}
function onWiringCreate(){}
function onNormal(){}
function onWiringDelete(){}
function onCreateServerPorts(){}



    